package com.xunua.NaoZiKongBai;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.tencent.mmkv.MMKV;
import com.xunua.NaoZiKongBai.Bean.Bmob.MyUser;
import com.xunua.NaoZiKongBai.Bean.EventBus.RealtimeloginstatusEvent;
import com.xunua.NaoZiKongBai.Bean.EventBus.Time60Event;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * @user XUNUA
 * @email xunua@outlook.com
 * @creat time 2020/5/12 23:01
 */
public class MyApplication extends Application {
    public static List<Activity> activityList=new ArrayList<>();
    private static int time60;//短信发送计时60秒
    public static boolean startRequest=true;//用于登录的时候验证。在发起登录请求的时候为false禁止验证账号token，登录成功后 且 将本地token同步到数据库中后，再继续进行登录状态更新

    @Override
    public void onCreate() {
        super.onCreate();
        MMKV.initialize(this);//mmkv初始化
        Logger.addLogAdapter(new AndroidLogAdapter());//logger初始化
        Bmob.initialize(getApplicationContext(),Constant.bomb_app_key);//初始化Bmob
        ActivityListen();//注册activity监听
//        Realtimeloginstatus();//监听登录状态
    }

    /**
     * 监听账号信息。  sdk的数据监听功能需要付费，因此决定还是定时查询数据库中的账号信息 如果与本地信息有差异，则退出登录。
     *
     *
     */
    private void Realtimeloginstatus() {
//        Observable.interval(0,3,TimeUnit.SECONDS)//period 间隔n秒后查询   用来查询用户是否修改了密码 或者在其它设备登录  一个月免费十万次api接口使用次数，这种行为尽量时间间隔长一点，后期再来改
//        .subscribeOn(Schedulers.io())
//                .observeOn(Schedulers.io())
//                .subscribe(new Consumer<Long>() {
//                    @Override
//                    public void accept(Long aLong) throws Exception {
//                        MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
//                        if (myUser != null&&startRequest) {
//                            BmobQuery<MyUser> bmobQuery = new BmobQuery<>();
//                            bmobQuery.addWhereEqualTo("username",myUser.getUsername());
//                            bmobQuery.findObjects(new FindListener<MyUser>() {
//                                @Override
//                                public void done(List<MyUser> list, BmobException e) {
//                                    if (e == null) {
//                                        if (list.get(0).getPwd_look().equals(myUser.getPwd_look())){
//                                            //密码一致
//                                            EventBus.getDefault().postSticky(new RealtimeloginstatusEvent(false));
////                                        log.e("登陆成功");
//                                            if (!list.get(0).getToken().equals("token")&&!list.get(0).getToken().equals(myUser.getToken())){
//                                                //异地登录  下线
//                                                BmobUser.logOut();//清除当前登录用户
//                                                EventBus.getDefault().postSticky(new RealtimeloginstatusEvent(true));
//                                            }
//                                        }else {
//                                            //密码出错
//                                            BmobUser.logOut();//清除当前登录用户
//                                            EventBus.getDefault().postSticky(new RealtimeloginstatusEvent(true));
////                                        log.e("密码出错");
//                                        }
//                                    }
//                                }
//                            });
//                        }else {
////                            log.e("已经退出登录");
//                        }
//                    }
//                });
    }

    private void ActivityListen(){
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                activityList.add(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                activityList.remove(activity);
            }
        });
    }

    public static void finishAllActivity(){
        for (Activity activity :
                activityList) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
        activityList.clear();
//        android.os.Process.killProcess(android.os.Process.myPid());//杀掉当前程序的进程，按需添加
    }

    public static void time60(){
        time60=60;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        EventBus.getDefault().postSticky(new Time60Event(time60--));
                        if (time60 < 0) {
                            this.cancel();
                            timer.cancel();
                        }
                    }
                },0,1000);
            }
        }).start();
    }
}
